package middleware

import (
	"github.com/gin-gonic/gin"
	"i18n-template/table"
	"i18n-template/utils"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(context *gin.Context) {
		token := context.GetHeader("authorization")
		if token == "" {
			utils.FailResponse(context, "验证令牌没有!", nil)
			return
		}
		encryptJwt, err := utils.ParseEncryptJwt(token)
		if !encryptJwt.Valid || err != nil {
			utils.FailResponse(context, "验证令牌过期!请重新登录.", nil)
			context.Abort()
			return
		}
		u, err := table.Users{}.FindUserByUsername(encryptJwt.Claims.(*utils.BuildEncryptJwt).Username)
		if err != nil {
			utils.FailResponse(context, "令牌验证失败, 用户不存在!", nil)
			context.Abort()
			return
		}
		u.Password = ""
		context.Set("user", u)
		context.Next()
	}
}
